package com.cupk.wudi.practice.apidemo.controller;

import com.cupk.wudi.practice.apidemo.entity.User;
import com.cupk.wudi.practice.apidemo.service.UserService;
import com.cupk.wudi.practice.apidemo.utils.Result;
import com.cupk.wudi.practice.apidemo.utils.TimeUtil;
import com.cupk.wudi.practice.apidemo.utils.TokenUtil;
import com.cupk.wudi.practice.apidemo.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Controller
@RestController
public class CommonController {

    @Autowired
    UserService userService;


    @GetMapping("/hello")
    Result<String> hello(){
        return Result.success("hello");
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        User user =null;
        Boolean flag=false;

        if(!StringUtils.isEmpty(loginVo.getName())){
//            System.out.println("-----------------------------------------------------------------");
            user= userService.getUserByName(loginVo.getName());

        }else if(loginVo.getId()!=null){
            user=userService.getUserById(loginVo.getId());
        }
//        System.out.println("------------------------------------------------------------------------------------------------");
//        System.out.println(user);
        if (user==null) {                           //USer判空
            return Result.error("用户不存在");
        }

        if(user.getPasswd().equals(loginVo.getPasswd())){    //密码检验
            flag=true;
        }
        if(flag){
            String token = TokenUtil.sign(user, TimeUtil.getCurrentTime()); //生成令牌
            return Result.success(token,"登陆成功");
        }else {
                return Result.error("密码错误");
            }
        }
    }



